import os
import random
import string
from urllib.parse import urlparse

import requests

domain1 = r'''weipan.sinaimg.cn
collection.sinaimg.cn
auto4.sinaimg.cn
auto.sinaimg.cn
auto2.sinaimg.cn
auto5.sinaimg.cn
video.sinaimg.cn
bjw.sinaimg.cn
neimenggu.sinaimg.cn
mjss.sinaimg.cn
z8.sinaimg.cn
heilongjiang.sinaimg.cn
hebei.sinaimg.cn
fj.sinaimg.cn
wximg4.sinaimg.cn
c.sinaimg.cn
zz.sinaimg.cn
z7.sinaimg.cn
z5.sinaimg.cn
z4.sinaimg.cn
z1.sinaimg.cn
auto3.sinaimg.cn
auto1.sinaimg.cn
gzw.sinaimg.cn
hainan.sinaimg.cn
comic.sinaimg.cn
m1.sinaimg.cn
hd.us.sinaimg.cn
fc.sinaimg.cn
ss2.sinaimg.cn
ss16.sinaimg.cn
ss9.sinaimg.cn
shanxiji.sinaimg.cn
s7.sinaimg.cn
s6.sinaimg.cn
s3.sinaimg.cn
portrait3.sinaimg.cn
p5.sinaimg.cn
p3.sinaimg.cn
p1.sinaimg.cn
lz.sinaimg.cn
zzx.sinaimg.cn
hubei.sinaimg.cn
govcity.sinaimg.cn
d8.sinaimg.cn
public.us.sinaimg.cn
a.sinaimg.cn
liaoning.sinaimg.cn
k.us.sinaimg.cn
jilin.sinaimg.cn
ipad.sinaimg.cn
wuxi.sinaimg.cn
wk.impress.sinaimg.cn
wbvip.us.sinaimg.cn
f.sinaimg.cn
wbox.sinaimg.cn
n0.sinaimg.cn
mu1.sinaimg.cn
z2.sinaimg.cn
wximg3.sinaimg.cn
wt.sinaimg.cn
tp4.sinaimg.cn
tc.sinaimg.cn
e2.sinaimg.cn
livephoto.us.sinaimg.cn
pkg.sinaimg.cn
s16.sinaimg.cn
ad.us.sinaimg.cn
ss3.sinaimg.cn
i.sinaimg.cn
2fwx4.sinaimg.cn
wx5.sinaimg.cn
s15.sinaimg.cn
l.sinaimg.cn
fashion.sinaimg.cn
s4.sinaimg.cn
portrait1.sinaimg.cn
r3.sinaimg.cn
ws4.sinaimg.cn
ws2.sinaimg.cn
ws3.sinaimg.cn
free.sinaimg.cn
ss7.sinaimg.cn
qingdao.sinaimg.cn
locallimit.us.sinaimg.cn
wxt.sinaimg.cn
tvax4.sinaimg.cn
ws1.sinaimg.cn
qcyn.sinaimg.cn
passport.sinaimg.cn
s8.sinaimg.cn
tva2.sinaimg.cn
tvax2.sinaimg.cn
s5.sinaimg.cn
r.sinaimg.cn
n3.sinaimg.cn
i1.sinaimg.cn
d9.sinaimg.cn
n1.sinaimg.cn
hunan.sinaimg.cn
sh.sinaimg.cn
sc.sinaimg.cn
i3.sinaimg.cn
jiangxi.sinaimg.cn
henan.sinaimg.cn
anhui.sinaimg.cn
guangxi.sinaimg.cn
portrait5.sinaimg.cn
i2.sinaimg.cn
tva4.sinaimg.cn
tvax1.sinaimg.cn
tav4.sinaimg.cn
f.us.sinaimg.cn
tp3.sinaimg.cn
tvax3.sinaimg.cn
s.us.sinaimg.cn
ss15.sinaimg.cn
ss1.sinaimg.cn
s11.sinaimg.cn
n2.sinaimg.cn
live.us.sinaimg.cn
s12.sinaimg.cn
k.sinaimg.cn
tva3.sinaimg.cn
wx1.sinaimg.cn
r0.sinaimg.cn
g.us.sinaimg.cn
wx2.sinaimg.cn
s10.sinaimg.cn
u1.sinaimg.cn
www.ww2.sinaimg.cn
wx3.sinaimg.cn
h5.sinaimg.cn
z0.sinaimg.cn
tva1.sinaimg.cn
wx4.sinaimg.cn
mjs.sinaimg.cn
n.sinaimg.cn
i0.sinaimg.cn
ww4.sinaimg.cn
zj.sinaimg.cn
s14.sinaimg.cn
tp1.sinaimg.cn
tp2.sinaimg.cn
s1.sinaimg.cn
us.sinaimg.cn
ww3.sinaimg.cn
vic.sinaimg.cn
gongyi.sinaimg.cn
ww2.sinaimg.cn
www.sinaimg.cn
ww1.sinaimg.cn
'''


def down():
    print("1")
    headers = {
        'Cookie': 'WEIBOCN_FROM=1110006030; _T_WM=27135833556; XSRF-TOKEN=890ec8; SCF=Ap6-CQv5tLaDuRtEKxh0f3DiCg9HvbIZ0aCFeIXDoITQwfwriQwALet855LzybJaX3w9Q1FIes9Ak9akiAq8BwY.; SUB=_2A25L77q7DeRhGeFJ71IU9y7PyjWIHXVohLJzrDV6PUJbktAGLVf6kW1Nf-c9Cjy0Rad7akYlow3FjutBxipzPPoG; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WhRhJAT2r6ndZ1LKSGoJBIJ5JpX5KMhUgL.FoMNSh5fS050eK.2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMNS0B7SKM7e024; SSOLoginState=1726728939; ALF=1729320939; MLOGIN=1; mweibo_short_token=f01d8e762e; M_WEIBOCN_PARAMS=luicode%3D20000174%26uicode%3D20000174'
    }

    resp = requests.get("https://weibo.com/ajax/profile/myhot?page=3&feature=2&uid=7894788820", headers=headers)
    # print(resp.status_code)
    # print(resp.text)
    thumbnail_urls = []
    for item in resp.json().get("data", {}).get("list", []):
        pic_infos = item.get("pic_infos", {})
        for pic_info in pic_infos.values():
            bmiddle_url = pic_info.get("largest", {}).get("url")
            if bmiddle_url:
                thumbnail_urls.append(bmiddle_url)  # 假设你只需要第一个 url，退出循环
    download_directory = 'C:/Users/Administrator/Desktop/wb4'
    os.makedirs(download_directory, exist_ok=True)

    for url in thumbnail_urls:
        try:
            print(url)
            re = requests.get(url)
            if re.status_code == 200:
                parsed_url = urlparse(url)
                filename = os.path.basename(parsed_url.path)
                name = os.path.join(download_directory, filename)
                with open(name, 'wb') as file:
                    file.write(re.content)
                    print(f"图片已保存到: {name}")
            else:
                print(f"下载失败，URL: {url}")
        except requests.RequestException as e:
            # 处理请求异常（如连接错误、超时等）
            print(f"下载失败，URL: {url}，错误信息: {e}")

        except Exception as e:
            # 处理其他异常
            print(f"处理文件失败，URL: {url}，错误信息: {e}")


def test():

    download_directory = 'C:/Users/Administrator/Desktop/wb1'
    os.makedirs(download_directory, exist_ok=True)

    characters = string.ascii_letters + string.digits
    for name in set(domain1.split('\n')):
        name = name.strip()
        if not name:
            continue
        url = f'http://{name}/wapb720/008ChJdygy1hsog7r0kfcj51e01y04jh2.jpg?KID=imgbed,photo&Expires=1758266205&ssig=c1Y4RVnLj2&uid=7740570319&referer=weibo.com'

        try:
            print(url)
            re = requests.get(url)
            if re.status_code == 200:
                parsed_url = urlparse(url)
                filename = os.path.basename(parsed_url.path)
                random_string = ''.join(random.choice(characters) for _ in range(10))
                name = os.path.join(download_directory, random_string+filename)
                with open(name, 'wb') as file:
                    file.write(re.content)
                    print(f"图片已保存到: {name}")
            else:
                print(f"下载失败，URL: {url}")
        except requests.RequestException as e:
            # 处理请求异常（如连接错误、超时等）
            print(f"下载失败，URL: {url}，错误信息: {e}")

        except Exception as e:
            # 处理其他异常
            print(f"处理文件失败，URL: {url}，错误信息: {e}")

def video():
    download_directory = 'C:/Users/Administrator/Desktop/wb12'
    os.makedirs(download_directory, exist_ok=True)

    characters = string.ascii_letters + string.digits
    url = "https://f.video.weibocdn.com/u0/yMYb5620gx08dWOdWUqs010412001xla0E010.mp4?label=mp4_720p&template=1280x720.25.0&media_id=5021274502529089&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=4&ot=h&lp=000022uNAc&ps=mZ6WB&uid=8rQDWn&ab=,8013-g0,3601-g39&Expires=1728967450&ssig=ryQoaZFCnz&KID=unistore,video"

    try:
        print(url)
        parsed_url = urlparse(url)
        filename = os.path.basename(parsed_url.path)
        with requests.get(url, stream=True) as response:
            response.raise_for_status()
            with open('C:/Users/Administrator/Desktop/wb12/1.mp4', 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    print("99999999")
                    file.write(chunk)

        print(f"视频已成功下载并保存为 {filename}")
    except requests.exceptions.RequestException as e:
        print(f"下载视频时出错: {e}")


def main():
    # down()
    # test()

    video()




if __name__ == '__main__':

    main()